/*
This file provides function 'connect_to_mars' which can be called to
establish a connection to the websocket server.

Example usage:
var mars = connect_to_mars("ws://localhost:8888/mars", onopen, onclose, onerror);
// onopen, onclose, onerror should be functions that tell the user what happens
mars.register_handler('T', got_temperature); // handle getting data tagged with T
mars.send('e5'); // send commands
*/
var connect_to_mars = function(ws_url, onopen, onclose, onerror) {
    var handlers = {};
    var ws = new WebSocket(ws_url);
    ws.onopen = function(ev) {
        console.log("WebSocket connection established.");
        if (onopen) onopen(ev);
    };
    ws.onclose = function(ev) {
        console.log("WebSocket connection closed.");
        if (onclose) onclose(ev);
    };
    ws.onerror = function(ev) {
        console.log("WebSocket had an error!.");
        if (onerror) onerror(ev);
    };
    ws.onmessage = function(ev) {
        var dataparts = ev.data.split(":");
        if (dataparts[0] in handlers)
            handlers[dataparts[0]](dataparts.slice(1));
        else
            console.log("Unhandled message "+ev.data);
    };
    return {
        register_handler: function(token, callback) {
            handlers[token] = callback;
        },
        close: function() {
            return ws.close();
        },
        send: function(data) {
            return ws.send(data);
        },
    };
};

